<template>
  <el-card class="user-table-container">
    <h2>用户管理系统界面</h2>

    <!-- 添加按钮 -->

    <el-button type="primary" @click="getUserList">查看所有用户的数据</el-button>
    <el-button type="primary" @click="openAddDialog">添加用户</el-button>
    <!-- 表格 -->
    <el-table :data="filteredUsers" style="width: 100%; margin-top: 20px" border>
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="age" label="年龄" width="80"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="phone" label="电话" width="150"></el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <el-button size="small" @click="editUser(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      layout="prev, pager, next"
      :total="users.length"
      :page-size="pageSize"
      @current-change="handlePageChange"
      style="margin-top: 20px"
    />

    <!-- 对话框：添加/编辑 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '添加用户'" width="40%">
      <el-form ref="formRef" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="0" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 模拟数据
const users = ref([
  { id: 1, name: "dkx", age: 1212, email: null, phone: null }
])

let currentId = ref(5) // 新用户 ID 自增起点
const dialogVisible = ref(false)
const isEdit = ref(false)

const form = ref({
  id: null,
  name: '',
  age: null,
  email: '',
  phone: ''
})

const formRef = ref()
const pageSize = ref(5)
const currentPage = ref(1)

//当页面刷新后请求users的数据

/* */

// 请求后端接口
// const getUserList = async () => {
//   try {
//     const response = await axios.get('http://localhost:8082/users') // 替换为你的接口地址
//     users.value = response.data
//   } catch (err) {
//     error.value = '获取数据失败，请检查网络或接口是否可用。'
//     console.error(err)
//   } finally {
//     loading.value = false
//   }
// }
import userApi from '@/api/userApi'

onMounted(async () => {
  const res = await userApi.getUsers()
  users.value = res.data
})


// 组件挂载时请求数据
// onMounted(() => {
//   getUserList()
// })

/** */
// 分页计算
const filteredUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return users.value.slice(start, start + pageSize.value)
})

// 打开添加对话框
function openAddDialog() {
  isEdit.value = false
  form.value = {
    id: null,
    name: '',
    age: null,
    email: '',
    phone: ''
  }
  dialogVisible.value = true
}

// 打开编辑对话框
function editUser(user) {
  isEdit.value = true
  form.value = { ...user }
  dialogVisible.value = true
}

// 删除用户
function deleteUser(id) {
  ElMessage.confirm('确定要删除此用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    users.value = users.value.filter(u => u.id !== id)
    ElMessage.success('删除成功')
  })
}

// 保存用户
function saveUser() {
  if (!isEdit.value) {
    // 添加
    users.value.push({ ...form.value, id: currentId.value++ })
    ElMessage.success('添加成功')
  } else {
    // 修改
    const index = users.value.findIndex(u => u.id === form.value.id)
    users.value[index] = { ...form.value }
    ElMessage.success('修改成功')
  }
  dialogVisible.value = false
}

// 分页切换
function handlePageChange(page) {
  currentPage.value = page
}

// 表单验证规则（可选）
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }]
}
</script>

<style scoped>
.user-table-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}
</style>